// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit.ula;

import com.dustedpixels.jasmin.unit.Unit;

/**
 * Provided with current row and column, current screen and attr bytes plus
 * current border and flash flag on input, it decodes current color index on
 * output.
 * 
 * <p>
 * This unit is designed to be connected directly to video decoder unit via
 * palette color decoder unit.
 * 
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class ColorDecoder implements Unit {
  // (input) clock source (7MHz)
  public boolean CLOCK;
  
  // (input) row and column numbers
  public int ROW;
  public int COL;
  
  // (input) screen, attr and border data
  public int SCREEN;
  public int ATTR;
  public int BORDER;
  public boolean FLASH;
  
  // (output) color
  public int COLOR;

  private boolean lastClock = false;
  private int screen;
  private int background;
  private int foreground;
  
  public void updateEndPoints() {
    if (lastClock  != CLOCK) {
      if (CLOCK) {
        if (ROW < 48) {
          if (COL < 48 + 256 + 48 + 8) {
            COLOR = BORDER;
          }
        } else if (ROW < 48 + 192) {
          if (COL < 48 + 8) {
            COLOR = BORDER;
          } else if (COL < 48 + 256 + 8) {
            if ((COL & 0x07) == 0) {
              screen = SCREEN;
              int rawBackground = ATTR >>> 3 & 0x0F;
              int rawForeground = (ATTR & 0x07) | (ATTR >>> 3 & 0x08);
              if ((ATTR & 0x80) == 0 || FLASH) {
                background = rawBackground;
                foreground = rawForeground;
              } else {
                background = rawForeground;
                foreground = rawBackground;
              }
            }
            COLOR = (screen & 0x80) == 0 ? background : foreground;
            screen <<= 1;
          } else if (COL < 48 + 256 + 48 + 8) {
            COLOR = BORDER;
          }
        } else if (ROW < 48 + 192 + 56) {
          if (COL < 48 + 256 + 48 + 8) {
            COLOR = BORDER;
          }
        }
      }
      lastClock = CLOCK;
    }
  }
}
